var MongoClient = require("mongodb").MongoClient;
let url = "mongodb://admin:admin@81.71.65.4:27017/server";

let Router = require("koa-router");
let router = new Router();
router.all("/", async (ctx) => {
  ctx.body = "hello world";
});
router.all("/add", async (ctx) => {
  let promiseObj = new Promise((resolve, reject) => {
    MongoClient.connect(url, function (err, db) {
      if (err) throw err;
      var dbo = db.db("server");
      var myobj = { name: "菜鸟教程", url: "www.runoob" };
      dbo.collection("hero").insertOne(myobj, function (err, res) {
        if (err) throw err;
        console.log("文档插入成功");
        resolve(res);
        db.close();
      });
    });
  });
  let res = await promiseObj;
  ctx.body = res;
});
router.all("/list", async (ctx) => {
  let promiseObj = new Promise((resolve, reject) => {
    MongoClient.connect(url, function (err, db) {
      if (err) throw err;
      var dbo = db.db("server");
      dbo
        .collection("hero")
        .find({})
        .toArray(function (err, result) {
          // 返回集合中所有数据
          if (err) throw err;
          console.log(result);
          resolve(result);
          db.close();
        });
    });
  });

  let res = await promiseObj;
  ctx.body = res;
});

module.exports = router;
